<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Util
 *
 * @author nmthong
 */
class Util {
    public static function Distance2Point($xA,$yA,$xB,$yB){
        //Khoang cach giua 2 diem AB
        return sqrt(($xA-$xB)*($xA-$xB)+($yA-$yB)*($yA-$yB));
    }
    
   public static function DistancePointToLine($xA,$yA,$xB,$yB,$xM,$yM){
       $kcAB=Util::getRealDistanceBetweenPoints($xA,$yA,$xB,$yB);
       $kcAM=Util::getRealDistanceBetweenPoints($xA,$yA,$xM,$yM);
       $kcBM=Util::getRealDistanceBetweenPoints($xB,$yB,$xM,$yM);
       return abs($kcAM+$kcBM-$kcAB);
    } 
    
    //return true : chay  ra xa ,false : chay lai gan
    public static function Direction($xPast,$yPast,$xCurrent,$yCurrent,$xM,$yM){
        $distance1=Util::Distance2Point($xPast,$yPast,$xM,$yM);
        $distance2=Util::Distance2Point($xCurrent,$yCurrent,$xM,$yM);
        if($distance2>=$distance1){
            return true;
        }else{
            return false;
        }
    }
    
       public static  function  getRealDistanceBetweenPoints($latitude1, $longitude1, $latitude2, $longitude2) {
            $theta = $longitude1 - $longitude2;
            $distance = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
            $distance = acos($distance);
            $distance = rad2deg($distance);
            $distance = $distance * 60 * 1.1515; 
            $distance = $distance * 1609.344;  
            return (round($distance,2));
       }   
       
       public static function getRealDistance2PointInRoute($index_pointA,$index_pointB,$route){
                if($index_pointA==$index_pointB){
                    return 0;
                }else if($index_pointA<$index_pointB){
                   $distance=0;
                   for($i=$index_pointA;$i<$index_pointB;$i++){
                        $pointA=$route[$i];
                        $pointB=$route[$i+1];
                        $distance=$distance+Util::getRealDistanceBetweenPoints($pointA->lat, $pointA->lng,$pointB->lat, $pointB->lng);
                        if($index_pointB==($i+1)) return $distance;
                    
                    }
                }else{
                   $distance=0;
                   for($i=$index_pointB;$i<$index_pointA;$i++){
                        $pointA=$route[$i];
                        $pointB=$route[$i+1];
                        $distance=$distance+Util::getRealDistanceBetweenPoints($pointA->lat, $pointA->lng,$pointB->lat, $pointB->lng);
                        if($index_pointA==($i+1)) return $distance;
                    
                    }                    
                }
           
       }
}

?>
